controllers.controller('RealTimeMapCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.heatmap = true;
    $scope.active = true;

    var w = 1024,
        h = 1024,
        fill = d3.scale.category20b();
    $scope.xScale = d3.scale.linear().domain([0, 2400]).range([61, 1008]);
    $scope.yScale = d3.scale.linear().domain([0, 1800]).range([63, 756]);
    $scope.reverseXScale = d3.scale.linear().domain([61, 1008]).range([0, 2400]);
    $scope.reverseYScale = d3.scale.linear().domain([63, 756]).range([0, 1800]);

    var data = new Array();
    var data2 = new Array();
    var X = new Array();
    var Y = new Array();

    var vis = d3.select('#chart')
        .attr('style', 'background-image: url(/assets/images/mapa.jpg); background-repeat: no-repeat;')
        .append('svg:svg')
        .attr('width', w)
        .attr('height', h);

    vis.on('click', function () {
        var coordinates = [0, 0];
        coordinates = d3.mouse(this);
        var x = $scope.reverseXScale(coordinates[0]);
        var y = $scope.reverseYScale(coordinates[1]);
        console.log(x,y);
    });

    // heatmap configuration
    var config = {
        element: document.getElementById("chart"),
        radius: 10,
        opacity: 50,
        width: w,
        height: h
    };

    //creates and initializes the heatmap
    var heatmap = h337.create(config);

    var add = function(x, y){
        heatmap.store.addDataPoint(x, y, 1);
    };

    setInterval(function() {
        if($scope.heatmap && $scope.active && $scope.tags){
            $scope.tags.forEach(function(d) {
                add(d.loc[0], d.loc[1]);
            })
        }
    }, 500);

    $scope.$watch('heatmap', function(newValue, oldValue) {
        if(!newValue){
            heatmap.clear();
        }
    })

    $http(jsRoutes.controllers.StationsController.getAllStations()).success(function(data, status, headers, config) {
        //sababa
        $scope.stations = data;
        $scope.stations.forEach(function(station) {
            vis.append("image")
                .attr("xlink:href", "assets/images/station.png")
                .attr("width", 30)
                .attr("height", 30)
                .attr("x", $scope.xScale(station.locationX))
                .attr("y", $scope.yScale(station.locationY))
                .attr("id", station.id)
                .on('click', function() {
                    var $this = d3.select(this);
                    $scope.station = $scope.stations.filter(function(station) {
                        return station.id == $this.attr("id");
                    })[0];
                    $scope.stationTags = $scope.station.tags;
                    $scope.stationInterval = setInterval(function() {
                        var openElemId = $('.collapse.in').parent('div.panel-default').attr('id');
                        $scope.stationTags = $scope.station ? $scope.station.tags : null;
                        $scope.$apply();
                        $('#'+openElemId+' a').trigger('click');
                    }, 10000);
                    $scope.$apply();
                })
                .append("svg:title")
                .text(station.name+" ("+station.locationX+","+station.locationY+")")

        })
    }).error(function(data, status, headers, config) {
        alert("error fetching stations")
    })

    function process_server(json) {
        data = [];
        data2 = [];
        X = [];
        Y = [];
        for (var i in json.tag) {
            var  tag = json.tag[i];
            if ( tag.button && tag.loc ) {
                data2.push(tag.id);
                X[tag.id] = $scope.xScale(tag.loc[0]);
                Y[tag.id] = $scope.yScale(tag.loc[1]);
            }
            data.push(tag.id);
        }
        vis.selectAll("circle")
            .data(json.tag, function(d) { return d.tagNumber; }).enter().append("svg:circle");
        vis.selectAll("circle")
            .data(json.tag, function(d) {return d.tagNumber;})
            .attr("class","orig").transition().duration(333)
            .attr("cx",function(d) {return d.loc ? d.loc[0]:0 ;})
            .attr("cy",function(d) {return d.loc ? d.loc[1]:0 ;})
            .attr("r",10)
            .attr("stroke","white")
            .attr("fill","blue")
            .attr("stroke-width",2);
        vis.selectAll("circle").append("svg:title")
            .text(function(d) {
                return d.tagNumber+" "+(d.objects.name || '')+" "+ (d.objects.description || '')+" "+ (d.objects.objectId || '');
            });

        vis.selectAll("circle").on('click', function(d) {
            $scope.$apply(function() {
                if($scope.station){
                    $scope.station = null;
                    clearInterval($scope.stationInterval);
                }
                $scope.tag = d
            });
        });
        vis.selectAll("circle")
            .data(json.tag, function(d) {return d.tagNumber;}).exit().remove();

        vis.selectAll("circle.pulse").remove();
        vis.selectAll("circle.pulse")
            .data(data2)
            .enter().append("svg:circle")
            .attr("class", "pulse")
            .attr("r",8)
            .attr("stroke","blue")
            .transition()
            .duration(333)
            .attr("cx",function(i) {return X[i];})
            .attr("cy",function(i) {return Y[i];})
            .attr("fill","transparent")
            .attr("stroke-width",2)
            .attr("r", 20)
            .style("stroke-opacity", 0.0);

    }

    function refresh_svg() {
        $http(jsRoutes.controllers.TagsController.getRealTimeTags()).success(function(data) {
            if(data){
                var json = {};

                json.tag = data.map(function(d){
                    d.loc = [$scope.xScale(d.locationX), $scope.yScale(d.locationY)];
                    return d;
                });
                if($scope.stations){
                    $scope.stations.forEach(function(station) {
                        station.tags = [];
                        json.tag.forEach(function (tag) {
                            if (tag.loc && tag.stationId == station.id) {
                                station.tags.push(tag);
                            }
                        });
                    });
                }
                process_server(json);
                $scope.tags = json.tag;
            }
        });

        if(window.location.hash.indexOf('realTimeMap') > -1){
            window.setTimeout(refresh_svg, 333);
        }else{
            $scope.active = false;
        }

    }

    refresh_svg();
}]);